package com.oceansoft.mobile.common.util;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.weixin.util.WeixinUtil;
import java.io.IOException;

/**
 * Created by liujie on 2017/5/18.
 * 防盗链工具包
 */
 public class SafeUrlUtils {


    /***
     * 验证链接可用性
     * @param wxwebencrytoken
     * @param sence_id
     * @param openid
     * @return
     */
    public static boolean CheckToken(String wxwebencrytoken,String sence_id,String openid){
        String access_token = WeixinUtil.getAccessToken(WeixinUtil.WXOPENID);
        String qqurl = "https://api.weixin.qq.com/cityservice/safeurl/checktoken?access_token="+access_token;
        JSONObject json = new JSONObject();
        json.put("wxwebencrytoken", wxwebencrytoken);
        json.put("sence_id",sence_id);
        json.put("openid", openid);
        json.put("access_token", access_token);
        try {
            String b = HttpClientUtil.post(qqurl,json);
            System.out.println(b);
            JSONObject result = JSONObject.parseObject(b);
            String errcode = String.valueOf(result.get("errcode"));
            if("0".equals(errcode)){
                return true;
            }else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    /***
     * 换取防盗链url
     * @param url
     * @param sence_id
     * @return
     */
    public static String GetSafeUrl(String url,String sence_id){
        String access_token = WeixinUtil.getAccessToken(WeixinUtil.WXOPENID);
        String qqurl = "https://api.weixin.qq.com/cityservice/safeurl/getpreurl?access_token="+access_token;
        JSONObject json = new JSONObject();
        json.put("url", url);
        json.put("sence_id",sence_id);
        try {
            String b = HttpClientUtil.post(qqurl,json);
            System.out.println(b);
            JSONObject result = JSONObject.parseObject(b);
            String errcode = String.valueOf(result.get("errcode"));
            if("0".equals(errcode)){
                return String.valueOf(result.get("enc_pre_url"));
            }else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /***
     * 判断防盗链范围
     * @param requestURI
     * @return
     */
    public static boolean checkUseSafeUrl(String requestURI){
        Object obj = CommonUtilCache.getItem(requestURI);
        if(obj == null){
            return false;
        }else{
            return true;
        }
    }

}
